package com.white.androidstudy.green;

import android.content.Context;
import android.text.TextUtils;

import com.white.androidstudy.main.AppContext;

/**
 * Created by ytf on 2017/2/28.
 * Description: GreenDao的数据库管理类
 */

public class GreenDaoManager
{
    private static GreenDaoManager instance;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    private static Context mContext;
    private String dbName;
    private static String lastUsedDbName = "";

    private GreenDaoManager(String dbName)
    {
        mContext = AppContext.getContext();
        this.dbName = dbName;
        init();
    }

    public static GreenDaoManager getInstance(String dbName)
    {
        //非空
        if(!TextUtils.isEmpty(dbName))
        {
            if(dbName.equals(lastUsedDbName))
            {
                if(instance == null)
                {
                    synchronized (GreenDaoManager.class)
                    {
                        if(instance == null)
                        {
                            instance = new GreenDaoManager(dbName);
                            lastUsedDbName = dbName;
                        }
                    }
                }
            }else
            {
                //如果数据库名字变动了，意思就是要在另外一个数据库操作,那么就要重新创建一个实例
                synchronized (GreenDaoManager.class)
                {
                    instance = new GreenDaoManager(dbName);
                    lastUsedDbName = dbName;
                }
            }
        }else
        {
            throw new IllegalArgumentException("dbName requried");
        }
        return instance;
    }

    /***
     * 初始化
     */
    private void init()
    {
        //字符串是数据库的名字
        CustomDevOpenHelper helper = new CustomDevOpenHelper(mContext, dbName);
        mDaoMaster = new DaoMaster(helper.getWritableDatabase());
        mDaoSession = mDaoMaster.newSession();
    }

    public DaoMaster getDaoMaster()
    {
        return mDaoMaster;
    }
    public DaoSession getDaoSession()
    {
        return mDaoSession;
    }
    public DaoSession getNewSession()
    {
        mDaoSession = mDaoMaster.newSession();
        return mDaoSession;
    }

}
